document.addEventListener('DOMContentLoaded', function() {
    try {
        const R = Math.random, d = document;
        let moves = 0;
        let startTime, timerInterval, pauseTime;
        const game = d.getElementById('game');
        const movesDisplay = d.getElementById('moves');
        const timeDisplay = d.getElementById('time');
        const bestScoreDisplay = d.getElementById('best-score');
        const pauseBtn = d.getElementById('pause-btn');
        const restartBtn = d.getElementById('restart-btn');
        const menu = d.getElementById('menu');
        const info = d.getElementById('info');
        let currentDifficulty = 'hard';
        let rows = 10, cols = 10;
        const bestScores = {
            easy: localStorage.getItem('bestScore_easy') || '暂无',
            medium: localStorage.getItem('bestScore_medium') || '暂无',
            hard: localStorage.getItem('bestScore_hard') || '暂无'
        };

        // 简化选择器
        const $ = function(x,c){return (c||d).querySelector(x)};
        const $$ = function(x,c){return Array.from((c||d).querySelectorAll(x))};
        const $T = function(x,y){return $('.tile.x'+x+'.y'+(y<0?'h':y))}; // 获取格子
        const lock = function(l){game.classList[l?'add':'remove']('lock')};

        // 创建格子
        function tile(x,y,v,t){
            t = document.createElement('button');
            t.className = 'tile';
            t.setPos = function(x,y){
                t.pos = {x:x, y:y};
                t.className = 'tile x'+x+' y'+(y<0?'h':y);
            };
            t.setVal = function(v){
                t.textContent = v; 
                t.style.backgroundColor = 'hsl('+((v*100)%360)+',100%,'+(20+v*5)+'%)';
                if(v == 0) {
                    t.textContent = "✓";
                    t.style.color = "green";
                }
            };
            t.setVal(v);
            t.setPos(x,y);
            return t;
        }

        // 移除格子
        function removeTile(t, cb, ex, h){
            t.classList.add('fade-out');
            setTimeout(function(){
                try{game.removeChild(t)}catch(ex){console.log(ex.message)}
                if(cb) cb();
            },100);
        }

        // 获取相邻相同数字的格子
        function getAdjacentTiles(t, t0, t1, l, D, v, r, i){
            r = [];
            v = parseInt(t.textContent);
            D = [-1,0, 1,0, 0,-1, 0,1]; // 上下左右
            for(i=0; i<4; i++){
                l = [D[i*2], D[i*2+1]];
                t1 = $T(t.pos.x + l[0], t.pos.y + l[1]);
                if(t1 && t1!=t0 && parseInt(t1.textContent)===v && !t1.classList.contains('sel')) {
                    t1.classList.add('sel');
                    r.push(t1);
                    r = r.concat(getAdjacentTiles(t1, t0?t0:t));
                }
            }
            return r;
        }

        // 检查是否胜利
        function checkWin() {
            const tiles = $$('.tile');
            const allZero = tiles.every(tile => tile.textContent === "✓");
            if(allZero) {
                stopTimer();
                const time = Math.floor((Date.now() - startTime) / 1000);
                const score = `${moves}步/${time}秒`;
                
                // 更新最佳成绩
                const prevBest = localStorage.getItem(`bestScore_${currentDifficulty}`);
                if (!prevBest || moves < parseInt(prevBest.split('步')[0])) {
                    localStorage.setItem(`bestScore_${currentDifficulty}`, score);
                    bestScores[currentDifficulty] = score;
                    bestScoreDisplay.textContent = score;
                }
                
                // 播放胜利音效
                const winSound = document.getElementById('win-sound');
                winSound.play();
                
                // 显示胜利信息
                const overlay = document.createElement('div');
                overlay.className = 'game-overlay';
                overlay.innerHTML = `
                    <div>恭喜获胜！</div>
                    <div>用时: ${time}秒</div>
                    <div>步数: ${moves}步</div>
                    <div>最佳成绩: ${localStorage.getItem(`bestScore_${currentDifficulty}`) || '暂无'}</div>
                    <button id="continue-btn">返回菜单</button>
                `;
                game.appendChild(overlay);
                
                document.getElementById('continue-btn').addEventListener('click', function() {
                    game.removeChild(overlay);
                    showMenu();
                });
            }
            return allZero;
        }

        function interAction(t, a, b, m){
            if (game.classList.contains('lock') || $$('.sel').length > 0 || game.classList.contains('paused')) return;
            m = parseInt(t.textContent) || 0;
            
            if(m > 0 && (a = getAdjacentTiles(t)).length > 0) {
                // 播放点击音效
                const clickSound = document.getElementById('click-sound');
                clickSound.currentTime = 0;
                clickSound.play();
                
                moves++;
                movesDisplay.textContent = moves;
                lock(true);
                
                (function removeTiles(){
                    if (a.length > 0) {
                        b = a.pop();
                        return removeTile(b, removeTiles);
                    }
                    t.setVal(m-1);
                    
                    (function fall(r, f, x, y, t){
                        f = 0;
                        // 先让所有格子下落
                        for(y = rows-1; y >= -1; y--) {
                            for(x = 0; x < cols; x++) {
                                if((t=$T(x,y)) && !$T(x,y+1) && y+1 < rows) {
                                    t.setPos(x,y+1);
                                    f++;
                                }
                            }
                        }
                        
                        if(f > 0) return setTimeout(function(){fall(r)}, 200);
                        
                        // 然后在顶部生成新格子
                        if(r > 0) {
                            for(x = 0; x < cols; x++) {
                                if(!$T(x,0) && R() < 0.5) {
                                    game.appendChild(tile(x, -1, Math.floor(7 + R() * 3)));
                                }
                            }
                            setTimeout(function(){fall(r-1)}, 200);
                        } else {
                            lock(false);
                            checkWin();
                        }
                    })(1);
                })();
            }
        }

        // 初始化游戏
        function initGame(r, c, difficulty) {
            currentDifficulty = difficulty;
            rows = r;
            cols = c;
            
            // 清除现有游戏
            game.innerHTML = '';
            moves = 0;
            movesDisplay.textContent = '0';
            timeDisplay.textContent = '0';
            bestScoreDisplay.textContent = bestScores[difficulty];
            
            // 设置网格尺寸
            const tileWidth = 100 / cols;
            const tileHeight = 100 / rows;
            
            // 动态生成CSS类
            const styleId = 'dynamic-tile-styles';
            let style = document.getElementById(styleId);
            if (!style) {
                style = document.createElement('style');
                style.id = styleId;
                document.head.appendChild(style);
            }
            
            style.textContent = `
                .tile {
                    width: ${tileWidth}vw;
                    height: ${tileHeight}vh;
                    font-size: ${Math.min(tileWidth, tileHeight) * 0.6}vh;
                    line-height: ${Math.min(tileWidth, tileHeight) * 0.8}vh;
                }
                ${Array.from({length: rows}, (_, i) => `
                .y${i} { top: ${i * tileHeight}vh; }
                `).join('')}
                ${Array.from({length: cols}, (_, i) => `
                .x${i} { left: ${i * tileWidth}vw; }
                `).join('')}
                .yh { top: -${tileHeight}vh; }
            `;
            
            // 创建格子
            for(let i = 0; i < cols; i++) {
                for(let j = 0; j < rows; j++) {
                    game.appendChild(tile(i, j, Math.floor(7 + R() * 3)));
                }
            }

            // 显示游戏界面
            menu.style.display = 'none';
            info.style.display = 'flex';
            startTimer();
        }
        
        function startTimer() {
            startTime = Date.now();
            timerInterval = setInterval(() => {
                timeDisplay.textContent = Math.floor((Date.now() - startTime) / 1000);
            }, 1000);
        }

        function stopTimer() {
            clearInterval(timerInterval);
        }
        
        function showMenu() {
            menu.style.display = 'flex';
            info.style.display = 'none';
            game.innerHTML = '';
            stopTimer();
        }

        // 添加游戏控制事件
        pauseBtn.addEventListener('click', function() {
            if(game.classList.contains('paused')) {
                game.classList.remove('paused');
                this.textContent = '暂停';
                startTime += Date.now() - pauseTime; // 调整开始时间以补偿暂停时间
                startTimer();
            } else {
                game.classList.add('paused');
                this.textContent = '继续';
                pauseTime = Date.now();
                stopTimer();
            }
        });
        
        restartBtn.addEventListener('click', function() {
            const r = currentDifficulty === 'easy' ? 5 : currentDifficulty === 'medium' ? 8 : 10;
            const c = currentDifficulty === 'easy' ? 5 : currentDifficulty === 'medium' ? 8 : 10;
            initGame(r, c, currentDifficulty);
        });

        // 添加难度选择事件
        document.getElementById('easy').addEventListener('click', function() {
            document.querySelector('#menu button.selected')?.classList.remove('selected');
            this.classList.add('selected');
            initGame(5, 5, 'easy');
        });
        
        document.getElementById('medium').addEventListener('click', function() {
            document.querySelector('#menu button.selected')?.classList.remove('selected');
            this.classList.add('selected');
            initGame(8, 8, 'medium');
        });
        
        document.getElementById('hard').addEventListener('click', function() {
            document.querySelector('#menu button.selected')?.classList.remove('selected');
            this.classList.add('selected');
            initGame(10, 10, 'hard');
        });

        // 默认选择困难模式
        document.getElementById('hard').classList.add('selected');

        // 添加事件监听
        game.addEventListener('click', function(e){
            if(e.target.classList.contains('tile')) {
                interAction(e.target);
            }
        });
        
        // 添加触摸支持
        game.addEventListener('touchstart', function(e){
            if(e.target.classList.contains('tile')) {
                e.preventDefault();
                interAction(e.target);
            }
        }, {passive: false});

    } catch (e) {
        console.error('游戏初始化失败:', e);
    }
});